package com.hxzy.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxzy.mapper.BookTypeMapper;
import com.hxzy.pojo.BookType;
import com.hxzy.service.BookTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.List;

/**
 * @author lzj
 * @create 2020-11-09 下午 4:53
 */
@Service
@Transactional
public class BookTypeServiceImpl implements BookTypeService {

    @Autowired
    private BookTypeMapper bookTypeMapper;
    @Autowired
    private JedisPool jedisPool;

    @Override
    public List<BookType> selectAll() {
        ObjectMapper mapper = new ObjectMapper();

        Jedis jedis = jedisPool.getResource();
        //（1）java应用首先从redis中查数据。
        String bookType = jedis.get("bookType");

        List<BookType> result = null;

        //（2）如果redis中有数据，查询成功。
        if (bookType!=null && bookType.length()>0){

            try {
                result = mapper.readValue(bookType, List.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            jedis.close();
            System.out.println("redis");
            return result;
        }else {
            //（3）如果redis中没有数据，则从数据库中查询。将数据保存在redis中，方便下次查询。
            List<BookType> selectAll = bookTypeMapper.selectAll();
            try {
                String s = mapper.writeValueAsString(selectAll);
                jedis.set("bookType",s);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            jedis.close();
            System.out.println("数据库");
            return selectAll;
        }

    }

    @Override
    public void add(BookType bookType) {
        bookTypeMapper.add(bookType);

        ObjectMapper mapper = new ObjectMapper();

        Jedis jedis = jedisPool.getResource();

        List<BookType> selectAll = bookTypeMapper.selectAll();
        try {
            String s = mapper.writeValueAsString(selectAll);
            jedis.set("bookType",s);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        jedis.close();
        System.out.println("数据库");
    }
}
